﻿using SysFrameWork;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.FrameEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace BLL
{
    public class TOrder : PubMethod
    {
        HttpAgreement http;
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        CuDbHelper cuHelper;
        List<InOutResult> resultList;

        public TOrder()
        {
            http = new HttpAgreement();
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            cuHelper = new CuDbHelper();
            resultList = new List<InOutResult>();
        }

        /// <summary>
        /// 更新token接口
        /// </summary>
        public ReturnResult refreshToken()
        {
            rsl = new ReturnResult();
            try
            {

            }
            catch (Exception ex )
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 产成品入库
        /// </summary>
        /// <param name="data">条码信息</param>
        /// <param name="usCode">提交人员信息</param>
        /// <returns></returns>
        public ReturnResult productReceive(DbProductBar data)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            List<InOutResult> resultList = new List<InOutResult>();
            List<string> bars = new List<string>();
            try
            {

                #region  读取token
                AutoTaskBLL auto = new AutoTaskBLL();
                var token = auto.GetSysFile("OpenToken");
                txt.AddLogMsg("获取token："+token);
                #endregion

                var pars = new Dictionary<string, object>();
                #region 构建参数
                var dto = new Dictionary<string, object>();
                dto["ExternalCode"] = data.barCode; //外部系统数据编号,后台做唯一性检查。
                // pars["Code"] = "001"; //单据编号
                var c_dic = new Dictionary<string, string>();
                c_dic["Code"] = "ST1002";
                dto["VoucherType"] = c_dic;//单据类型。固定值:{Code: "ST1002"}

                dto["VoucherDate"] = data.happenDate;

                c_dic = new Dictionary<string, string>();
                c_dic["Code"] = "03";
                dto["BusiType"] = c_dic;//业务类型。默认值： { Code: "03"}

                c_dic = new Dictionary<string, string>();
                c_dic["Code"] = data.wareHouse;
                dto["Warehouse"] = c_dic;//仓库。默认值： { Code: "03"}

                c_dic = new Dictionary<string, string>();
                c_dic["Code"] = data.Department;
                dto["Department"] = c_dic;//部门
                dto["Memo"] = "物控生成";

                var RDRecordDetails = new List<Dictionary<string, object>>();
                var detail= new Dictionary<string, object>();

                var Inventory = new Dictionary<string, string>();
                Inventory["Code"] =data.proCode;

                detail["Code"] = "0001";
                detail["Inventory"] = Inventory;
                detail["BaseQuantity"] = data.proWeight;
                detail["quantity2"] = "1";//件数
                RDRecordDetails.Add(detail);
                dto["RDRecordDetails"] = RDRecordDetails;//明细信息
                pars["dto"] = dto;
                #endregion
                var postData = JsonConvert.SerializeObject(pars);

                txt.AddLogMsg("T+参数构建完成，参数内容："+postData);
                var msg = http.HttpPost(ConfigReader.Reader["peUrl"], postData,token);
                if (msg == "null")
                {
                    rsl.Result = true;
                }
                else
                {
                    txt.AddLogMsg("T+接口异常，接口结果内容：" + msg);
                    rsl.Message=JsonConvert.DeserializeObject<JObject>(msg)["message"].ToString();
                    rsl.Result = false;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        /// <summary>
        /// 销售出库
        /// </summary>
        /// <param name="tempDatas"></param>
        /// <param name="usCode"></param>
        /// <returns></returns>
        public ReturnResult SaleOutWareHouse(List<DbTempScanData> tempDatas, string baseCode, string usCode)
        {
            rsl = new ReturnResult();
            resultList = new List<InOutResult>();
            try
            {
                if (string.IsNullOrWhiteSpace(tempDatas[0].tempCode))
                {
                    rsl.Result = false;
                    rsl.Message = "传入的临时码为空";
                    return rsl;
                }
                txt.AddLogMsg("销售出库单开始执行");
                List<string> tempCodes = new List<string>();
                var pars = new Dictionary<string, object>();
                string msg = "";
                var paraData = this.wareOutData(tempDatas[0].tempCode, baseCode, ref msg);
                var data = (List<Dictionary<string, string>>)paraData["dataList"];
                var bars = (List<string>)paraData["barList"];
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                if (bars == null || bars.Count <= 0)
                {
                    rsl.Result = false;
                    rsl.Message = "没有获取调用接口的数据条码";
                    return rsl;
                }
             

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 其他出库数据
        /// </summary>
        /// <param name="tempCode"></param>
        /// <returns></returns>
        private Dictionary<string, object> wareOutData(string tempCode, string baseCode, ref string errMsg)
        {
            Dictionary<string, object> returnDic = new Dictionary<string, object>();
            List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>();
            StringBuilder sb = new StringBuilder();
            sb.Append("select tempInfo.*,us.userName, ");
            sb.Append(" isnull(barInfo.number,'0') as barNumber,");
            sb.Append("barInfo.U8relationCode AS U8Code,");
            sb.Append("barInfo.color color,barInfo.trademark shangbiao,barInfo.cu_baozhuang baozhuang,  ");
            sb.Append("barInfo.cu_guohao guohao,  ");
            sb.Append("barInfo.cu_customer customName,barInfo.cuCode barCustomCode,invInfo.cu_xianggui xianggui,");
            sb.Append(" invInfo.proCode,invInfo.proName,invInfo.spec,invInfo.mUnit,");
            sb.Append(" invInfo.mUnitName,invInfo.cUnit,invInfo.cUnitName,isnull(invInfo.bFrees,'') bFrees  ");
            sb.Append(" from (select * from bar_TempScanData_info  ");
            sb.Append(" where 1=1 ");
            sb.Append(" and tempCode='" + tempCode + "')");
            sb.Append(" tempInfo ");
            //sb.Append(" LEFT  JOIN bar_ProductBarCode_info  barInfo ON tempInfo.barCode = barInfo.barCode");
            sb.Append(" LEFT  JOIN V_BarCode_Sub_Info  barInfo ON barInfo.barCode = tempInfo.barCode");
            //sb.Append(" LEFT  JOIN fun_CommonData_Info  cu ON cu.cCode = barInfo.cu_customer");
            //sb.Append(" and cu.isDel=0 and cu.status='Y' and cu.specFile='" + baseCode + "'");
            sb.Append(" LEFT  JOIN V_Products_info  invInfo ON invInfo.proCode = barInfo.proCode");
            sb.Append(" and invInfo.baseCode='" + baseCode + "' and invInfo.isDel=0 and invInfo.status='Y'");
            sb.Append(" LEFT  JOIN sys_users_info  us ON tempInfo.createuser = us.userCode");
            sb.Append(" and us.baseCode='" + baseCode + "' and us.isDel=0 and us.status='Y'");


            var table = cmd.GetDataTable(sb.ToString());

            List<string> reList = new List<string>();
            List<string> barList = new List<string>();
            Dictionary<string, string> dic;
            var irow = 0;

            foreach (DataRow r in table.Rows)
            {
               
            }
            returnDic.Add("barList", barList);
            returnDic.Add("dataList", dataList);
            return returnDic;
        }



    
        /// <summary>
        /// u8接口登录信息参数构建
        /// </summary>
        /// <param name="uTable"></param>
        /// <returns></returns>
        public Dictionary<string, object> createUserPar(string userCode, string baseCode, ref string errMsg)
        {
            StringBuilder sb = new StringBuilder();
            //var sAccID = Tools.ConfigReader.Reader["sAccID"];//账套号
            var sAccID = baseCode;
            var sys = new Dictionary<string, object>();
            sys["sAccID"] = sAccID;
            sys["sYear"] = DateTime.Now.Year;
            sys["sDate"] = getNowDate();
            sys["sServer"] = Tools.ConfigReader.Reader["BaseServerIP"];
            if (userCode == "admin")
            {
                sys["sUserID"] = "521";
                sys["sUserName"] = "独宇航";
                sys["sPassword"] = "123456";

            }
            else
            {
                sb.Append("select * from sys_users_info where userCode='" + userCode + "'");
                sb.Append(" and isSync='Y' and isDel='0' and status='Y' ");
                sb.Append(" and baseCode='" + sAccID + "'");
                var uTable = cmd.GetDataTable(sb.ToString());
                if (uTable.Rows.Count < 1)
                {
                    errMsg = "该账号无权限提交数据";
                    return null;
                }
                sys["sUserID"] = uTable.Rows[0]["userCode"].ToString();
                sys["sUserName"] = uTable.Rows[0]["userName"].ToString();
                if (string.IsNullOrWhiteSpace(uTable.Rows[0]["openPwd"].ToString()))
                {
                    errMsg = "系统密码与U8密码不匹配请先修改密码";
                    return null;
                }
                sys["sPassword"] = Tools.Encryption.DesDecrypt(uTable.Rows[0]["openPwd"].ToString());
            }

            return sys;
        }
   
    }
}
